﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace SocketServer
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 1.创建服务端Socket对象
            Socket socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress iPAddress = IPAddress.Parse("127.0.0.1");
            IPEndPoint iPEndPoint = new IPEndPoint(iPAddress, 10086);
            socketServer.Bind(iPEndPoint);
            // 开始侦听(等待客户端发出连接),并设置最大客户端连接数为10
            socketServer.Listen(10);
            // 阻塞，等待客户端去连接
            //Socket socket = socketServer.Accept();
            Task.Run(() => { Accept(socketServer); });

            //byte[] buffer = new byte[1024 * 1024];
            //// 接收消息
            //int length = socket.Receive(buffer, 0, buffer.Length, SocketFlags.None);
            //string msg = Encoding.UTF8.GetString(buffer, 0, length);
            //Console.WriteLine($"服务端收到消息:{msg}\r\n");

            Console.ReadKey();
        }

        static void Accept(Socket socket)
        {
            while (true)
            {
                // 等待客户端连接
                Socket newSocket = socket.Accept();
                Task.Run(() => { Recive(newSocket); });
            }
        }

        static void Recive(Socket newSocket)
        {
            while (true)
            {
                byte[] buffer = new byte[1024 * 1024];
                // 接收消息
                int length = newSocket.Receive(buffer, 0, buffer.Length, SocketFlags.None);
                string msg = Encoding.UTF8.GetString(buffer, 0, length);
                Console.WriteLine($"服务端收到消息:{msg}\r\n");

                newSocket.Send(Encoding.UTF8.GetBytes("==============你好,客户端=============================================="));
            }

        }
    }
}
